<?php
/**
 * @author Feng
 * @date 2012-6-19
 */
class collection_collect_controller extends system_user_ajaxControl {
	
	protected $a = null;
	protected $_setting = array();
	public function init() {
		if(!parent::init()) {
			return;
		}
		$this->a = trim($this->_post('action'));
		$this->_setting = $this->_post('setting');
	}
	
	protected function collectPhoto(collection_special_row $row, $spage = 1) {
		$page = intval($this->_post('page'));
		$this->_data->complete = false;
		$collecter = new collection_collect_special($row);
		try {
			if(!($pages = $this->_post('pages'))) {
				$pages = $collecter->getPages();
				if(count($pages) <= 0) {
					$pages = array($row->getUrl());
				}
				$_link = $this->link($pages[0]);
				$this->_data->message = "TOTAL PAGE: " . $this->bold(count($pages)) . " , COLLECTTING {$this->bold($row->getTitle())}: $_link ..";
				$this->_data->params = array('action' => 'collect-photo', 'pages' => serialize($pages), 'page' => '1', 'spage' => $spage);
				if(1 && $item = $row->getItem()) {
					$row->getItem()->setParams($this->_data->params)->update();
				}
				$iparams = $this->_data->params;				
				unset($iparams['spage']);
				$row->setParams($iparams)->update();
				$this->_output();
			}
			$pages = unserialize($pages);
			$this->_data->params = array('action' => 'collect-photo', 'page' => ($page + 1), 'pages' => serialize($pages), 'spage' => $spage);
			if(count($pages) <= 0) {
				$this->_data->params = array('action' => 'collect-photo', 'spage' => ($spage + 1));
				$this->_data->message = "{$this->bold($row->getTitle())} CELLECTED COMPLETE, GOTO NEXT SPECIAL ..";
				if(1 && $item = $row->getItem()) {
					$row->getItem()->setParams($this->_data->params)->update();
				}
				$iparams = $this->_data->params;				
				unset($iparams['spage']);
				$row->setParams($iparams)->update();
				$this->_output();
			}
			$page = $page - 1;
			if(isset($pages[$page])) {
				$photos = $collecter->setPages($pages)->setPage($page)->Collect();
				if(1 && $errors = $collecter->getError() && !empty($errors)) {
					$this->addMessage('<p class="red">' . implode('</p><p class="red">', $errors) . '</p>');
				}
				$_page = $page + 1;
				// 保存到数据库
				$this->savePhoto($row, $photos, $_page);
				$_total = count($pages);
				$_message = "[$_page/$_total] " . $this->blue('COMPLETE') . "! TOTAL: " . $this->bold(count($photos)) . " PHOTOS.";
				if(isset($pages[$_page])) {
					$_message .= "TRYING TO COLLECT: " . $this->link($pages[$_page]) . " ..";
				} else {
					$_message .= "TRYING TO COLLECT NEXT PAGE ..";
				}
				$this->_data->message = $_message;
			} else {
				$this->_data->message = "{$this->bold($row->getTitle())} CELLECTED COMPLETE, GOTO NEXT SPECIAL ..";
				$this->_data->params = array('action' => 'collect-photo', 'spage' => ($spage + 1)); // 没有分页了，下一步
			}
			if(1 && $item = $row->getItem()) {
				$row->getItem()->setParams($this->_data->params)->update();
			}
			$iparams = $this->_data->params;				
			unset($iparams['spage']);
			$row->setParams($iparams)->update();
			$this->_output();
		} catch (Exception $e) {
			$_params = array('action' => 'collect-photo', 'error' => $e->getMessage(), 'spage' => $spage + 1);
			$msg = "AN ERROR OCCURRED： {$this->red($e->getMessage())}";
			if($this->getSetting('ignore_error')) {
				$this->addMessage($msg);
				$this->_data->params = $_params;
			} else {
				$this->_error($msg);
			}
			try {
				if(1 && $item = $row->getItem()) {
					$row->getItem()->setParams($_params)->update();
				}
				$row->setParams($_params)->update();
				$_msg = addslashes($e->getMessage());
				$_params = addslashes(serialize($_params));
				$_time = system_date::timestamp();
				$_link = system_encrypt::shortUrl($collecter->getCurrentUrl());
				system_db::getAdapter()->query("INSERT INTO `collection_error`(`message`, `link`, `params`, `creationtime`) VALUES('$_msg', '$_link', '$_params', '$_time')");
			} catch (Exception $ex) {
				$this->addMessage($this->red($ex->getMessage()));
			}
			$this->_output();
		}
	}
	
	protected function collectSpecial(collection_item_row $row) {
		$page = intval($this->_post('page'));
		$this->_data->complete = false;
		$collecter = new collection_collect_item($row);
		try {
			if(!($pages = $this->_post('pages'))) {
				$pages = $collecter->getPages();
				if(count($pages) <= 0) {
					$pages = array($row->getUrl());
				}
				$_link = $this->link($pages[0]);
				$this->_data->message = "TOTAL PAGE: " . $this->bold(count($pages)) . " , COLLECTTING: $_link ..";
				$this->_data->params = array('action' => 'collect-special', 'pages' => serialize($pages), 'page' => '1');
				$row->setParams($this->_data->params)->update();
				$this->_output();
			}
			$pages = unserialize($pages);
			$this->_data->params = array('action' => 'collect-special', 'page' => ($page + 1), 'pages' => serialize($pages));
			if(count($pages) <= 0) {
				$this->_data->params = array('action' => 'collect-photo');
				$this->_data->message = "SPECIALS CELLECTED COMPLETE, START TO COLLECT PHOTOS ..";
				$row->setParams($this->_data->params)->update();
				$this->_output();
			}
			$page = $page - 1;
			if(isset($pages[$page])) {
				$specials = $collecter->setPages($pages)->setPage($page)->Collect();
				if(1 && $errors = $collecter->getError() && !empty($errors)) {
					$this->addMessage('<p class="red">' . implode('</p><p class="red">', $errors) . '</p>');
				}				
				// 保存到数据库
				$this->saveSpecial($row, $specials);
				
				$_page = $page + 1;			
				$_total = count($pages);
				$_message = "[$_page/$_total] " . $this->blue('COMPLETE') . "! TOTAL: " . $this->bold(count($specials)) . " SPECIALS.";
				if(isset($pages[$_page])) {
					$_message .= "TRYING TO COLLECT: " . $this->link($pages[$_page]) . " ..";
				} else {
					$_message .= "TRYING TO COLLECT NEXT PAGE ..";
				}
				$this->_data->message = $_message;
			} else {
				$this->_data->message = "ALL PAGES CELLECTED, START TO COLLECT PHOTOS ..";
				$this->_data->params = array('action' => 'collect-photo'); // 没有分页了，下一步
			}
			$row->setParams($this->_data->params)->update();
			$this->_output();
		} catch (Exception $e) {
			$msg = "AN ERROR OCCURRED： {$this->red($e->getMessage())}";
			if($this->getSetting('ignore_error')) {
				$this->addMessage($msg);
				$this->_data->params = array_merge((array)$this->_data->params, array('error' => $e->getMessage()));
			} else {
				$this->_error($msg);
			}
			try {
				$_msg = addslashes($e->getMessage());
				$_params = addslashes(serialize($this->_data->params));
				$_time = system_date::timestamp();
				$_link = system_encrypt::shortUrl($collecter->getCurrentUrl());
				system_db::getAdapter()->query("INSERT INTO `collection_error`(`message`, `link`, `params`, `creationtime`) VALUES('$_msg', '$_link', '$_params', '$_time')");
			} catch (Exception $ex) {
				$this->addMessage($this->red($ex->getMessage()));
			}
			$this->_output();
		}
	}
	
	private function savePhoto(collection_special_row $row, array $photos, $_pageindex) {
		$keys = array_keys($photos);
		if(empty($keys)) {
			return;
		}
		$links = $imports = $photos;
		$_key = "'" . implode("', '", $keys) . "'";
		foreach(system_db::getAdapter()->query("SELECT `link` FROM `collection_photo` WHERE `link` IN($_key) AND `special_id` = '{$row->getId()}'") AS $a) {
			unset($photos[$a['link']]); // 已经存在的PHOTO删除
		}
		foreach(system_db::getAdapter()->query("SELECT `key` FROM `resource_link` WHERE `key` IN($_key)") AS $a) {
			unset($links[$a['key']]); // 已经存在的链接删除
		}
		if(!empty($photos)) {
			$sql = "INSERT INTO `collection_photo`(`hash`, `link`, `special_id`, `title`, `description`, `creationtime`) VALUES";
			$time = system_date::timestamp();
			foreach($photos as $key => $photo) {
				$title = addslashes(trim($photo['title']));
				$description = addslashes(trim($photo['description']));
				$hash = trim($photo['hash']);
				$sql .= "('$hash', '$key', '{$row->getId()}', '$title', '$description', '$time'),";
			}
			system_db::getAdapter()->query(trim($sql, ','));
		}
		if(!empty($links)) {
			$sql = "INSERT INTO `resource_link`(`key`, `url`) VALUES";
			foreach($links as $key => $link) {
				$url = addslashes(trim($link['url']));
				$sql .= "('$key', '$url'),";
			}
			system_db::getAdapter()->query(trim($sql, ','));
		}
		/**
		 * 自动导入
		 */
		if($this->getSetting('auto_import_photo')) {
			foreach(system_db::getAdapter()->query("SELECT `link_key` FROM `picture_photo_collection` WHERE `link_key` IN($_key)") AS $a) {
				unset($imports[$a['link_key']]); // 已经存在的链接删除
			}
			if(!empty($imports)) {
				try {
					system_db::getAdapter()->beginTransaction();
					if(!($pscRow = system_db::getAdapter()->fetchRow("SELECT `special_id` FROM `picture_special_collection` WHERE `link_key` = '{$row->getLink()}'"))) {
						throw new collection_exception("Collectted Images can not Import into the Special({$this->bold($row->getTitle())}),because the Special is not Imported.");
					}
					$special_id = $pscRow['special_id'];
					// photo 主表
					$sql = "INSERT INTO `picture_photo`(`hash`, `creationtime`, `lastmodified`) VALUES";
					$_time = system_date::timestamp();
					$_ttls = array();
					$_ii = 0;
					$_firstHash = '';
					foreach($imports as $key => $import) {
						$_hash = $import['hash'];
						if($_ii == 0) $_firstHash = $_hash;
						$sql .= "('$_hash', '$_time', '$_time'),";
						$_ttls[] = array('link' => $key, 'title' => addslashes(trim($import['title'])), 'description' => addslashes(trim($import['description'])));
						$_ii++;
					}
					system_db::getAdapter()->query(trim($sql, ','));
						
					// photo 语言表
					rsort($_ttls);
					$lang = $this->user->getLang();
					$limit = count($imports);
					$_locale = $_description = array();
					$_ccSql = "";
					$_cpSql = "";
					foreach(system_db::getAdapter()->query("SELECT `id` FROM `picture_photo` ORDER BY `id` DESC LIMIT $limit") AS $key => $a) {
						if(!isset($_ttls[$key])) continue;
						$_pid = $a['id'];
						$_lnk = $_ttls[$key]['link'];
						$_title = $_ttls[$key]['title'] ? $_ttls[$key]['title'] : "{$row->getTitle()}($_pageindex)";
						$_locale[$_pid] = $_title;
						$_description[$_pid] = $_ttls[$key]['description'];
						$_ccSql .= "('$_lnk', '$_pid', '$_time'),";
						$_cpSql .= "('$special_id', '$_pid'),";
					}
					if(!empty($_locale)) {
						$sql = "INSERT INTO `picture_photo_locale`(`photo_id`, `lang`, `title`, `description`) VALUES";						
						foreach($_locale as $pid => $title) {
							$desc = isset($_description[$pid]) ? $_description[$pid] : '';
							$sql .= "('$pid', '$lang', '$title', '$desc'),";
						}
						system_db::getAdapter()->query(trim($sql, ','));
					}
					if(strlen($_ccSql) > 0) {
						$sql = "INSERT INTO `picture_photo_collection`(`link_key`, `photo_id`, `lastcollected`) VALUES " . trim($_ccSql, ",");
						system_db::getAdapter()->query($sql);
					}
					if(strlen($_cpSql) > 0) {
						$sql = "INSERT INTO `picture_special_photo`(`special_id`, `photo_id`) VALUES " . trim($_cpSql, ",");
						system_db::getAdapter()->query($sql);
					}
					//更新专辑图片数量
					$concept = new picture_special_localeConcept();
					if(1 && $_sRow = $concept->fetch(array('special.id = ?' => $special_id))) {
						$_sRow->updatePhotoCount();
						if($_pageindex <= 1) {
							$_sRow->set('cover', $_firstHash);
							$_sRow->update();
						}
					}
					system_db::getAdapter()->commit();
					$this->addMessage("IMPORTED: " . $this->bold(implode(', ', $_locale)));
				} catch (Exception $e) {
					system_db::getAdapter()->rollBack();
					throw $e;
				}
			} else {
				$this->addMessage($this->blue("NO LINE") . " IMPORTED");
			}
		}
	}
	
	private function saveSpecial(collection_item_row $row, array $specials) {
		$keys = array_keys($specials);
		if(empty($keys)) {
			return;
		}
		$links = $imports = $specials;
		$_key = "'" . implode("', '", $keys) . "'";
		foreach(system_db::getAdapter()->query("SELECT `link` FROM `collection_special` WHERE `link` IN($_key)") AS $a) {
			unset($specials[$a['link']]); // 已经存在的SPECIAL删除
		}
		foreach(system_db::getAdapter()->query("SELECT `key` FROM `resource_link` WHERE `key` IN($_key)") AS $a) {
			unset($links[$a['key']]); // 已经存在的链接删除
		}
		if(!empty($specials)) {
			$sql = "INSERT INTO `collection_special`(`link`, `item_id`, `title`, `rule_id`, `params`, `creationtime`) VALUES";
			$time = system_date::timestamp();
			foreach($specials as $key => $special) {
				$title = addslashes(trim($special['title']));
				$sql .= "('$key', '{$row->getId()}', '$title', '{$row->getSpecialRuleId()}', 'a:0:{}', '$time'),";
			}
			system_db::getAdapter()->query(trim($sql, ','));
		}
		if(!empty($links)) {
			$sql = "INSERT INTO `resource_link`(`key`, `url`) VALUES";
			foreach($links as $key => $link) {
				$url = addslashes(trim($link['url']));
				$sql .= "('$key', '$url'),";
			}
			system_db::getAdapter()->query(trim($sql, ','));
		}
		/**
		 * 自动导入
		 */
		if($this->getSetting('auto_import_special')) {
			foreach(system_db::getAdapter()->query("SELECT `link_key` FROM `picture_special_collection` WHERE `link_key` IN($_key)") AS $a) {
				unset($imports[$a['link_key']]); // 已经存在的链接删除
			}
			if(!empty($imports)) {
				try {
					system_db::getAdapter()->beginTransaction();
					// special 主表
					$sql = "INSERT INTO `picture_special`(`name`, `creationtime`, `lastmodified`) VALUES";
					$_time = system_date::timestamp();
					$_ttls = array();
					foreach($imports as $key => $import) {
						$_name = system_encrypt::createIdByTime();
						$sql .= "('$_name', '$_time', '$_time'),";
						$_ttls[] = array('link' => $key, 'title' => addslashes(trim($import['title'])), 'description' => addslashes(trim($import['description'])));
					}
					system_db::getAdapter()->query(trim($sql, ','));
					
					$categories = array();
					foreach(system_db::getAdapter()->query("SELECT `category_id` FROM `collection_item_category` WHERE `item_id` = '{$row->getId()}'") AS $a) {
						$categories[$a['category_id']] = $a['category_id'];
					}					
					
					// special 语言表
					rsort($_ttls);
					$lang = $this->user->getLang();
					$limit = count($imports);
					$_locale = $_description = array();
					$_cvSql = "";
					$_ccSql = "";
					$_udSql = array();
					foreach(system_db::getAdapter()->query("SELECT `id` FROM `picture_special` ORDER BY `id` DESC LIMIT $limit") AS $key => $a) {
						if(!isset($_ttls[$key])) continue;
						$_sid = $a['id'];
						$_lnk = $_ttls[$key]['link'];
						$_locale[$_sid] = $_ttls[$key]['title'];
						$_description[$_sid] = $_ttls[$key]['description'];
						$_ccSql .= "('$_lnk', '$_sid', '$_time'),";
						foreach($categories AS $category_id) {
							$_cvSql .= "('{$this->user->getLang()}', '$_sid', '$category_id'),";
							$_udSql[$category_id] = "UPDATE `picture_category_locale` SET `stotal` = (
											SELECT COUNT(1) FROM `picture_special_category` WHERE `category_id` = '$category_id' AND `lang` = '$lang'
										) WHERE `lang` = '$lang' AND `category_id` = '$category_id'";
						}
					}
					if(!empty($_locale)) {
						$sql = "INSERT INTO `picture_special_locale`(`special_id`, `lang`, `title`, `description`) VALUES";
						foreach($_locale as $sid => $title) {
							$desc = isset($_description[$sid]) ? $_description[$sid] : '';
							$sql .= "('$sid', '$lang', '$title', '$desc'),";
						}
						system_db::getAdapter()->query(trim($sql, ','));
					}
					if(strlen($_ccSql) > 0) {
						$sql = "INSERT INTO `picture_special_collection`(`link_key`, `special_id`, `lastcollected`) VALUES " . trim($_ccSql, ",");
						system_db::getAdapter()->query($sql);
					}
					if(strlen($_cvSql) > 0) {
						$sql = "INSERT INTO `picture_special_category`(`lang`, `special_id`, `category_id`) VALUES " . trim($_cvSql, ",");
						system_db::getAdapter()->query($sql);
					}
					// 前后順序
					foreach($_udSql AS $_uds) {
						system_db::getAdapter()->query($_uds);
					}				
					system_db::getAdapter()->commit();
					$this->addMessage("IMPORTED: " . $this->bold(implode(', ', $_locale)));
				} catch (Exception $e) {
					system_db::getAdapter()->rollBack();
					throw $e;
				}
			} else {
				$this->addMessage($this->blue("NO LINE") . " IMPORTED");
			}
		}
	}
	
	protected function getSetting($name, $def = null) {
		$name = strtolower($name);
		return isset($this->_setting[$name]) ? $this->_setting[$name] : $def;
	}
	
	protected function bold($txt) {
		return '<strong class="red">' . $txt . '</strong>';
	}
	
	protected function link($url) {
		return '<a href="' . $url . '" target="_blank">' . $url . '</a>';
	}
	
	protected function blue($txt) {
		return '<span class="blue">' . $txt . '</span>';
	}
	
	protected function red($txt) {
		return '<span class="red">' . $txt . '</span>';
	}

}
